import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;


public class JDBCInsert {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源对象，数据源对象就描述了要访问的数据库是啥？在哪？
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/2022_11_06?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("hzj2003717");

        //2.让代码与数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要插入的学号:");
        int id = scanner.nextInt();
        System.out.println("请输入要插入的姓名:");
        String name = scanner.next();

        //3.构造要执行SQL语句[使用占位符？]
        String sql = "insert into student values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println("statement:"+ statement);

        //4.执行SQL[发送请求&读取响应]
        int n = statement.executeUpdate();
        System.out.println("n= "+n);

        //5.完成之后需要关闭释放相关资源
        statement.close();
        connection.close();
    }
}
